//
// Copyright (c) 2014, 保留所有权利。
//
// ApiServiceImpl.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 上午12:01:55
//
// 
//
package com.common.api;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.common.api.ApiService.Iface;
import com.common.api.handler.ApiHandler;
import com.common.api.handler.FollowRecordHandler;
import com.common.api.handler.LockHandler;
import com.common.api.handler.MappingHandler;
import com.common.api.handler.MergeHandler;
import com.common.api.handler.RestoreHandler;
import com.vanke.agent.common.log.LoggerUtil;

/**
 *
 */
public class ApiServiceImpl implements Iface {
	Logger log = LoggerUtil.getLoggerByName("api_invoke");
	private String FNAME_HEADER = "header";
	private String FNAME_CMD = "cmd";

	@Override
	public String invoke(String arg) {
		log.info("api request: " + arg);
		try {
			JSONObject json = JSONObject.fromObject(arg);
			if (!json.containsKey(FNAME_HEADER)) {
				return missingParam(FNAME_HEADER).toString();
			}
			JSONObject header = json.getJSONObject(FNAME_HEADER);
			if (!header.containsKey(FNAME_CMD)) {
				return missingParam(FNAME_HEADER, FNAME_CMD).toString();
			}
			String cmd = header.getString(FNAME_CMD);
			ApiHandler handle = createHandler(cmd);
			if (handle == null) {
				return genErr(1003, "不支持的请求方式").toString();
			}
			JSONObject result = handle.handle(json);
			if (result == null) {
				return genErr(1005, "系统处理失败").toString();
			}
			return result.toString();
		} catch (Exception e) {
			log.error(e);
			return genErr(-1, "未知错误").toString();
		}
	} //~invoke

	private JSONObject missingParam(String... params) {
		String ps = "";
		for (String param : params) {
			ps += param + "/";
		}
		if (ps.charAt(ps.length() - 1) == '/') {
			ps = ps.substring(0, ps.length() - 1);
		}
		return genErr(1001, "缺少必须参数[" + ps + "]");
	}

	/* 创建API处理器 */
	private ApiHandler createHandler(String cmd) {
		if (cmd == null) {
			return null;
		}
		cmd = cmd.trim();
		if ("merge".equals(cmd)) {
			return new MergeHandler();
		}
		if ("restore".equals(cmd)) {
			return new RestoreHandler();
		}
		if ("update_mapping".equals(cmd)) {
			return new MappingHandler();
		}
		if ("lock".equals(cmd)) {
			return new LockHandler();
		}
		if ("follow_query".equals(cmd)) {
			return new FollowRecordHandler();
		}
		return null;
	}

	private JSONObject genErr(int code, String msg) {
		JSONObject json = new JSONObject();
		json.put("errcode", code);
		json.put("errmsg", msg);
		return json;
	}

}
